<script lang="ts" setup>
import { ref, unref, watch } from 'vue'
import { Form } from 'ant-design-vue'
import { useI18n } from '@/hooks/web/useI18n'
import { isEmpty } from '@/utils/is'

const { t } = useI18n()
const { id, onFieldChange, onFieldBlur } = Form.useInjectFormItemContext()
const emit = defineEmits(['update:value', 'change', 'input', 'blur'])

const props = defineProps({
  value: { type: Array as PropType<Recordable[]>, default: () => [] },
  iconSize: { type: Number, default: 32 },
  span: { type: Number, default: 8 },
  dataType: { type: String, default: 'default' }
})

const widthStyle = `width: calc(100% - ${props.iconSize + props.span}px)`
const initTypeValue = {
  default: undefined,
  string: '',
  array: [],
  rate: 0,
  bool: false
}
const initValue = initTypeValue[props.dataType]
const collection = ref<Recordable[]>([
  { value: initValue, __key__: new Date().getTime() }
])
const init = (): void => {
  if (!props.value.length) {
    collection.value = [
      { value: initValue, __key__: new Date().getTime() }
    ] as Expandable[]
    return
  }
  collection.value = props.value.map((item, index) => ({
    value: item,
    __key__: new Date().getTime() + index
  })) as Expandable[]
}

watch(
  (): any => props.value,
  () => {
    let initState =
      !unref(collection).length ||
      !props.value.length ||
      (unref(collection).length === 1 &&
        unref(collection)[0].value === initValue &&
        props.value.length)
    if (initState) init()
  }
)

const getCurrentValue = () => {
  if (
    unref(collection).length === 1 &&
    unref(collection)[0].value === initValue
  ) {
    return []
  }
  return unref(collection).map(item => item.value)
}

const onAddItem = () => {
  unref(collection).push({
    value: initValue,
    __key__: new Date().getTime()
  })
  emit('update:value', getCurrentValue())
  onFieldChange()
}

const onDeleteItem = (__key__: number) => {
  if (unref(collection).length === 1) {
    return
  }
  collection.value = unref(collection)?.filter(
    (item: any) => item.__key__ !== __key__
  )
  emit('update:value', getCurrentValue())
  onFieldChange()
  onFieldBlur()
}

const onBlur = (val: Recordable, index: number) => {
  if (isEmpty(val)) {
    collection.value[index].value = initValue
  }
  emit('update:value', getCurrentValue())
  emit('blur')
  onFieldBlur()
}
const onChange = (val: Recordable, index: number) => {
  collection.value[index].value = val
  emit('update:value', getCurrentValue())
  emit('change', getCurrentValue())
  onFieldChange()
}
</script>

<template>
  <a-space
    :id="id"
    size="large"
    direction="vertical"
    style="width: 100%"
    class="system-collection-wrapper"
  >
    <a-row
      v-for="(item, index) in collection"
      :key="item.__key__"
      :gutter="8"
      align="middle"
      class="system-collection-item"
    >
      <a-col :style="widthStyle">
        <slot :index="index" :method="{ onBlur, onChange }"></slot>
      </a-col>
      <a-col>
        <minus-circle-outlined
          class="system-collection-delete-btn"
          :style="{
            cursor: collection.length === 1 ? 'not-allowed' : 'pointer'
          }"
          @click="onDeleteItem(item.__key__)"
        />
      </a-col>
    </a-row>
    <a-button type="dashed" :style="widthStyle" @click="onAddItem">
      <PlusOutlined />
      {{ t('common.add') }}
    </a-button>
  </a-space>
</template>

<style lang="less" scoped>
.system-collection-delete-btn {
  font-size: 24px;
  color: #999;
  transition: all 0.3s;

  &:hover {
    color: #777;
  }
}
</style>